package service

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/os/gtime"
	"websocket/internal/consts"
	"websocket/internal/websocket"
)

type sWebsocketLogic struct {
}

var (
	insWebsocketLogic = sWebsocketLogic{}
)

func WebsocketLogic() *sWebsocketLogic {
	return &insWebsocketLogic
}

func (s *sWebsocketLogic) Clients(ctx context.Context) interface{} {
	clients := websocket.Assemble().GetClients(ctx)
	for unique := range clients {
		_ = websocket.Manager().WriteMsg(ctx, unique, websocket.Manager().BuildRes(ctx, &consts.WebsocketWorkRes{
			Cmd:    consts.WebsocketCmdBroadcastServerDatetime,
			Code:   0,
			Msg:    "ok",
			Unique: unique,
			Data: g.Map{
				"server_datetime": gtime.Datetime(),
			},
		}))
	}
	return clients
}

func (s *sWebsocketLogic) BroadcastServerDatetime(ctx context.Context) {
	clients := websocket.Assemble().GetClients(ctx)
	loggerCtx := websocket.Context().InitLogger(websocket.ContextLogger{
		ClientTraceId: gctx.CtxId(ctx),
		TraceId:       gctx.CtxId(ctx),
		UpTime:        gtime.Now(),
		Original:      "",
	}, ctx)
	for unique := range clients {
		_ = websocket.Manager().WriteMsg(loggerCtx, unique, websocket.Manager().BuildRes(loggerCtx, &consts.WebsocketWorkRes{
			Cmd:    consts.WebsocketCmdBroadcastServerDatetime,
			Code:   0,
			Msg:    "ok",
			Unique: unique,
			Data: g.Map{
				"server_datetime": gtime.Datetime(),
			},
		}))
	}
}
